/**
 * 网络请求
 */
import env from '@/utils/env.js'
import user from '@/store/index.js'

function service(options = {}, loading) {
	const copyOptions = { ...options }
	const token = uni.getStorageSync('token');
	options.url = `${env.baseUrl}${options.url}`;
	options.header = {
		'content-type': 'application/json',
		'token': token ? token : ''
	}

	return new Promise((resolved, rejected) => {
		options.success = (res) => {
			switch (res.statusCode) {
				case 200:
					resolved(res.data)
					break;
				case 401:
					user.dispatch('user/silentLogin', copyOptions, true).then(res => {
						resolved(res)
					})
					break;
				default:
					reject(res)
					break;
			}
		}
		options.fail = (err) => {
			rejected(err)
		}
		options.complete = () => {
			if (loading) {
				uni.hideLoading();
			}
		}
		uni.request(options);
		if (loading) {
			uni.showLoading({
				title: '加载中'
			});
		}
	})
}

// uni.addInterceptor('request', {
// 	// 请求前拦截
// 	invoke(requestConfig) {
// 		const token = uni.getStorageSync('token');
// 		if (token) {
// 			requestConfig.header['token'] =  token;
// 		}

// 		return requestConfig
// 	},
// 	// 请求后拦
// 	returnValue(res) {
// 	}
// })

export default service;
